<template>
  <div class="permission-management">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">授权管理</el-breadcrumb-item>
      <el-breadcrumb-item>应用权限</el-breadcrumb-item>
    </el-breadcrumb>

    <el-row class="content-row">
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>选择应用</span>
          </div>
          <el-menu mode="vertical" :default-active="activeIndex" class="el-menu-vertical-demo" @select="handleSelect">
            <el-menu-item v-for="(item, index) in applications" :key="item.uuid" :index="String(index)">
              {{ item.name }}
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>权限设置 - {{ currentApp ? currentApp.name : '' }}</span>
            <el-button-group style="float: right;">
              <el-button type="primary" @click="savePermissions">保存</el-button>
              <el-button @click="cancelChanges">取消</el-button>
            </el-button-group>
          </div>
          <el-table :data="routerData" style="width: 100%">
            <el-table-column label="全部授权" width="100">
              <template slot="header">
                <el-checkbox 
                  v-model="selectAll" 
                  @change="handleSelectAllChange"
                  :indeterminate="isIndeterminate">
                  全部授权
                </el-checkbox>
              </template>
              <template slot-scope="scope">
                <el-checkbox
                  v-model="scope.row.authorized"
                  @change="(val) => handleAuthChange(scope.row, val)">
                </el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="服务名称" width="180"></el-table-column>
            <el-table-column prop="descript" label="描述" width="180">
              <template slot-scope="scope">
                <el-tooltip :content="scope.row.descript" placement="top">
                  <span class="truncate">{{ scope.row.descript }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="predicate" label="路径" width="180">
              <template slot-scope="scope">
                <el-tooltip :content="scope.row.predicate" placement="top">
                  <span class="truncate">{{ scope.row.predicate }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="授权状态" width="100">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.authorized"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="(val) => handleAuthChange(scope.row, val)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="过期时间（未填写视为永久）" width="240">
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.expirationTime"
                  type="datetime"
                  placeholder="选择过期时间"
                  :disabled="!scope.row.authorized"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  @change="handleExpirationChange(scope.row)">
                </el-date-picker>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listApp } from '@/api/gatewayadmin/app';
import { patchAdd, getRouterByAppid } from '@/api/gatewayadmin/permission';
import { listRouter } from '@/api/gatewayadmin/router';

export default {
  name: 'PermissionManagement',
  data() {
    return {
      activeIndex: '0',
      currentApp: null,
      applications: [],
      routerData: [],
      loading: false,
      total: 0,
      permissionData: [], // 用于存储 getRouterByAppid 返回的数据
      selectAll: false,
      isIndeterminate: false,
    }
  },
  methods: {
    async handleSelect(index) {
      this.currentApp = this.applications[index];
      await this.loadRouterForApp(this.currentApp.uuid);
    },
    async savePermissions() {
      try {
        this.loading = true;

        // 首先检查是否有变更
        const changedPermissions = this.routerData.filter(item => 
          item.originalAuthorized !== item.authorized ||
          item.originalExpirationTime !== item.expirationTime
        );

        if (changedPermissions.length === 0) {
          this.$message.info('没有变更需要保存');
          this.loading = false;
          return;
        }

        // 只有在有变更时才重新获取最新的权限数据
        const latestPermissionResponse = await getRouterByAppid(this.currentApp.uuid);
        const latestPermissionData = latestPermissionResponse.data || [];

        const permissionsToUpdate = changedPermissions.map(item => {
          const permissionItem = latestPermissionData.find(p => p.routerId === item.uuid);
          return {
            uuid: permissionItem ? permissionItem.uuid : '',
            appId: this.currentApp.uuid,
            routerId: item.uuid,
            expiration: item.expirationTime || '',
            checked: item.authorized,
            changeType: item.authorized ? '1' : '2'
          };
        });

        console.log('Patching permissions:', permissionsToUpdate);

        await patchAdd(permissionsToUpdate);
        this.$message.success(`${this.currentApp.name}的权限设置已保存`);

        // 更新原始状态和权限数据
        this.permissionData = latestPermissionData;
        this.routerData.forEach(item => {
          item.originalAuthorized = item.authorized;
          item.originalExpirationTime = item.expirationTime;
        });

        // 重新加载路由数据以确保显示最新状态
        await this.loadRouterForApp(this.currentApp.uuid);
      } catch (error) {
        this.$message.error('保存失败，请重试');
        console.error('保存权限时出错:', error);
      } finally {
        this.loading = false;
      }
    },
    cancelChanges() {
      this.loadRouterForApp(this.currentApp.uuid);
      this.$message.info(`已取消${this.currentApp.name}的更改`);
    },
    async loadApplications() {
      try {
        this.loading = true;
        const response = await listApp({
          pageNum: 1,
          pageSize: 100
        });
        this.applications = response.rows;
        this.total = response.total;
        if (this.applications.length > 0) {
          this.currentApp = this.applications[0];
          await this.loadRouterForApp(this.currentApp.uuid);
        }
      } catch (error) {
        this.$message.error('加载应用列表失败，请重试');
        console.error('加载应用列表时出错:', error);
      } finally {
        this.loading = false;
      }
    },
    async loadRouterForApp(appUuid) {
      try {
        this.loading = true;
        const [routerResponse, permissionResponse] = await Promise.all([
          listRouter({
            appId: appUuid,
            pageNum: 1,
            pageSize: 100
          }),
          getRouterByAppid(appUuid)
        ]);

        if (routerResponse.code === 200 && routerResponse.rows) {
          this.permissionData = permissionResponse.data || [];
          const authorizedRouterMap = new Map(
            this.permissionData.map(item => [item.routerId, item])
          );

          this.routerData = routerResponse.rows.map(item => {
            const permissionItem = authorizedRouterMap.get(item.uuid);
            const authorized = !!permissionItem;
            return {
              ...item,
              authorized,
              expirationTime: permissionItem ? permissionItem.expiration : null,
              originalAuthorized: authorized,
              originalExpirationTime: permissionItem ? permissionItem.expiration : null
            };
          });
          this.total = routerResponse.total;
          this.updateSelectAllStatus();
          console.log('Router data loaded:', this.routerData); // 添加日志
        } else {
          throw new Error(routerResponse.msg || '加载路由数据失败');
        }
      } catch (error) {
        this.$message.error('加载路由数据失败，请重试');
        console.error('加载路由数据时出错:', error);
      } finally {
        this.loading = false;
      }
    },
    handleAuthChange(row, val) {
      console.log(`服务 ${row.name} 的授权状态变更为: ${val}`);
      row.authorized = val;
      if (!val) {
        row.expirationTime = null;
      }
      this.$nextTick(() => {
        this.updateSelectAllStatus();
      });
    },
    handleExpirationChange(row) {
      console.log(`服务 ${row.name} 的过期时间变更为: ${row.expirationTime}`);
    },
    handleSelectAllChange(val) {
      console.log('Select all changed:', val); // 添加日志
      this.selectAll = val;
      this.isIndeterminate = false;
      this.routerData.forEach(item => {
        item.authorized = val;
        if (!val) {
          item.expirationTime = null;
        }
      });
      this.$nextTick(() => {
        this.updateSelectAllStatus();
      });
    },
    updateSelectAllStatus() {
      if (this.routerData.length === 0) {
        this.selectAll = false;
        this.isIndeterminate = false;
        return;
      }
      
      const authorizedCount = this.routerData.filter(item => item.authorized).length;
      this.selectAll = authorizedCount === this.routerData.length;
      this.isIndeterminate = authorizedCount > 0 && authorizedCount < this.routerData.length;
      
      console.log('Select all status updated:', {
        selectAll: this.selectAll,
        isIndeterminate: this.isIndeterminate,
        authorizedCount,
        totalCount: this.routerData.length
      }); // 添加日志
    }
  },
  mounted() {
    this.loadApplications();
  }
}
</script>

<style scoped>
.permission-management {
  padding: 20px;
}
.content-row {
  margin-top: 20px;
}
.box-card {
  height: 100%;
}
.el-menu-vertical-demo {
  height: 100%;
}
.el-checkbox {
  margin-right: 10px;
}
.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
  max-width: 100%;
}
</style>
